# from django.shortcuts import render
import hashlib
import json

import os
from django.conf import settings

from lib.http import render_json
from user.models import User,Permission,Roles,RolePermRelation
from user.logic import send_verify_code,check_vcode
from common import error
from common import tools
from MyQR import myqr

def login(request):
  if request.method=='POST':
    json_str = request.body
    if not json_str:
      result = {'code': 202, 'error': 'Please POST data!!!'}
      return render_json(result)
    # 如果当前报错，请执行json_str.decode
    json_obj = json.loads(json_str)
    print(json_obj)
    phonenum = json_obj.get('username')
    passwd = json_obj.get('password')
    # print(phonenum,passwd)
    is_phonenum=User.objects.filter(phonenum=phonenum)

    if not is_phonenum:
      result = {'code': 106, 'error': 'The username is not exist!!!'}
      return render_json(result,code=106)
    key=is_phonenum[0].key
    # 生成密码hash
    user_passwd=tools.hmac_md5(key,passwd)
    if is_phonenum[0].passwd != user_passwd:
      result = {'code': 107, 'error': 'The username or password is wrong!!!'}
      return render_json(result,code=107)


    user=User.objects.get(phonenum=phonenum)

    return render_json(data=user.to_dict(),code=200)


def users(request):
  if request.method=='GET':
    # user=request.user
    # print('user:',user)
    query_username=request.GET.get('query')
    if query_username:
      users=User.objects.filter(phonenum__icontains=query_username)
      res = [user.to_dict() for user in users]
      result = {"data": res}
      # print('users:',users)
      return render_json(data=result)
    pagenum=int(request.GET.get('pagenum'))
    pagesize=int(request.GET.get('pagesize'))
    # print(pagenum,pagesize)
    start=(pagenum-1)*pagesize
    end=start+pagesize
    users=User.objects.all()[start:end]
    res=[user.to_dict() for user in users]
    total = User.objects.all().count()
    result={"data":res,'total':total}
    # print('users:',users)
    return render_json(data=result)

  elif request.method=='POST':
    try:
      json_str = request.body
      if not json_str:
        result = {'code': 202, 'error': 'Please POST data!!!'}
        return render_json(result)
      # 如果当前报错，请执行json_str.decode
      json_obj = json.loads(json_str)
      print(json_obj)
      user_id = json_obj.get('user')

      user=User.objects.get(id=user_id)
      state = json_obj.get('state')
      user.state=state
      user.save()
      return render_json('success')
    except Exception as e:
      print(e)
      print('failed')
      return render_json('failed',code=1001)

#获取验证码
def get_verify_code(request):
  #手机注册
  json_str = request.body
  if not json_str:
    result = {'code': 202, 'error': 'Please POST data!!!'}
    return render_json(result)
  # 如果当前报错，请执行json_str.decode
  json_obj = json.loads(json_str)
  print('*************',json_obj)
  phonenum = json_obj.get('phonenum')
  print('*************', phonenum)
  if send_verify_code(phonenum):
    return render_json('verify code successed send')
  else:
    return render_json('sorry,verify code sended, 3min after delay',code=1)

#用户注册
def adduser(request):
  """注册或者管理员添加用户"""
  if not request.method == 'POST':
    result = {'code': 102, 'error': 'Please use POST !'}
    return render_json(result,code=102)

  json_str = request.body
  print('+',json_str)
  if not json_str:
    result = {'code': 103, 'error': 'Please give me json'}
    return render_json(result,code=103)

  json_obj = json.loads(json_str)
  phonenum = json_obj.get('phonenum')
  nickname=json_obj.get('nickname')
  password = json_obj.get('passwd')
  jypasswd=json_obj.get('jypasswd')
  # recommed_nickname = json_obj.get('recommed_nickname')
  recommed_phone = json_obj.get('recommed_phone')
  vcode = json_obj.get('vcode')
  print(phonenum,vcode,type(vcode))
  if check_vcode(phonenum, vcode):
    old_user = User.objects.filter(phonenum=phonenum)
    if old_user:
      result = {'code': 106, 'error': 'The username is used !!'}
      return render_json(result,code=106)
    #生成密码hash
    key,passwd=tools.salt_passwd(password)
    jykey,jypass=tools.salt_passwd(jypasswd)
    # jypass=tools.hmac_md5(key,jypasswd)
    try:
      User.objects.create(phonenum=phonenum,nickname=nickname, passwd=passwd,
                          key=key,jykey=jykey,jypasswd=jypass,recommend=recommed_phone)
      res={'phonenum':phonenum,
      'key':key,
      'jykey':jykey}
      return render_json(data=res)
    except Exception as e:
      print('----create error is %s' % (e))
      result = {'code': 107, 'error': 'Sorry, server is busy !'}
      return render_json(result,code=107)
  else:
    return render_json('verify_code check failed',code=108)

def search_id(request):
  json_str = request.body
  if not json_str:
    result = {'code': 202, 'error': 'Please POST data!!!'}
    return render_json(result)
  # 如果当前报错，请执行json_str.decode
  json_obj = json.loads(json_str)
  print(json_obj)
  user_id = json_obj.get('user_id')

  user = User.objects.get(id=user_id)
  return render_json(user.to_dict())

def modify_user_passwd(request):
  """修改用户的登录密码"""
  json_str = request.body
  if not json_str:
    result = {'code': 203, 'error': 'Please POST data!!!'}
    return render_json(result)
  json_obj = json.loads(json_str)
  print(json_obj)
  phonenum = json_obj.get('phonenum')
  password = json_obj.get('password')
  vcode = json_obj.get('vcode')
  if check_vcode(phonenum, vcode):
    # 生成密码hash
    key, passwd = tools.salt_passwd(password)
    try:
      User.objects.filter(phonenum=phonenum).only('passwd','key').update(passwd=passwd,key=key)
      result = {'res': 'modify user passwd successed','keys':key}
      return render_json(result)
    except:
      result = {'code': 1, 'res': 'modify user passwd failed'}
      return render_json(data=result, code=1)
  else:
    return render_json('verify_code check failed', code=2)

def modify_user_jypasswd(request):
  """修改用户的交易密码"""
  json_str = request.body
  if not json_str:
    result = {'code': 203, 'error': 'Please POST data!!!'}
    return render_json(result)
  json_obj = json.loads(json_str)
  print(json_obj)
  phonenum = json_obj.get('phonenum')
  jypassword = json_obj.get('jypassword')
  vcode = json_obj.get('vcode')
  # key = json_obj.get('key')
  if check_vcode(phonenum, vcode):
    # 生成密码hash
    key, passwd = tools.salt_passwd(jypassword)
    # passwd = tools.hmac_md5(key,jypassword)
    try:
      User.objects.filter(phonenum=phonenum).only('jypasswd','jykey').update(jypasswd=passwd,jykey=key)
      result = {'res': 'modify user jypasswd successed','jykeys':key}
      return render_json(result)
    except:
      result = {'code': 1, 'res': 'modify user passwd failed'}
      return render_json(data=result, code=1)
  else:
    return render_json('verify_code check failed', code=2)

def delete_user(request):
  if request.method == 'DELETE':
    print('11111')
    user_id = request.GET.get('id')
    print(user_id)
    if user_id:
      try:
        user_obj=User.objects.get(id=user_id)
        user_obj.delete()
        return render_json('删除用户成功')
      except:
        return render_json('删除用户失败',code=204)

def modify_profile(request):
  """查询个人信息：nickname avatar"""
  json_str = request.body
  if not json_str:
    result = {'code': 203, 'error': 'Please POST data!!!'}
    return render_json(result)
  json_obj = json.loads(json_str)
  phonenum = json_obj.get('phonenum')
  profile = User.objects.filter(phonenum=phonenum).only('nickname','avatar','user_price')
  # print(profile[0].nickname)
  res={'nickname':profile[0].nickname,'avatar':profile[0].avatar,'user_price':profile[0].user_price}
  return render_json(data=res)

#生成注册邀请码
def generate_register_ewm(phone):
  """生成注册邀请码"""
  filename='register_ewm.png'
  filepath = os.path.join(settings.BASE_DIR, settings.MEDIA_ROOT, phone)
  _filepath = os.path.join(filepath, filename)
  if not os.path.exists(_filepath):
    myqr.run(
      words='http://127.0.0.1:8080/#/pages/register/register?phone={}'.format(phone),
      # 扫描二维码后，显示的内容，或是跳转的链接
      # version=5,  # 设置容错率
      # level='H',  # 控制纠错水平，范围是L、M、Q、H，从左到右依次升高
      # picture='../',  # 图片所在目录，可以是动图
      # colorized=True,  # 黑白(False)还是彩色(True)
      # contrast=1.0,  # 用以调节图片的对比度，1.0 表示原始图片。默认为1.0。
      # brightness=1.0,  # 用来调节图片的亮度，用法同上。
      save_name=filename,  # 控制输出文件名，格式可以是 .jpg， .png ，.bmp ，.gif
      save_dir=filepath
    )
  return _filepath
def get_register_ewm(request):
  """获取注册邀请码"""
  json_str = request.body
  if not json_str:
    result = {'code': 203, 'error': 'Please POST data!!!'}
    return render_json(result)
  json_obj = json.loads(json_str)
  phone = json_obj.get('phone')
  filepath=generate_register_ewm(phone)
  result = {'code': 200, 'res': filepath}
  return render_json(data=result)

def profile_img(request):
  """修改用户头像"""
  phone = request.POST.get('phone')
  print(phone)
  file = request.FILES.get('avata')
  type(file)
  print(file.name.split('.')[-1])
  print(file.name)
  filename='avatar'+'.'+file.name.split('.')[-1]
  if file:
    filepath = os.path.join(settings.BASE_DIR, settings.MEDIA_ROOT, phone)
    if not os.path.exists(filepath):
      os.makedirs(filepath)
    _filepath = os.path.join(filepath, filename)
    print(_filepath)
    with open(_filepath,'wb') as newfile:
      for chunk in file.chunks():
        newfile.write(chunk)
    #将文件路径写入数据库avatar字段中
    User.objects.filter(phonenum=phone).update(avatar=_filepath)
    result = {'code': 200, 'res': '修改用户头像成功!!!'}
    return render_json(data=result)

def upload_wxShouKuanMa(request):
  """上传微信收款码"""
  phone = request.POST.get('phone')
  print(phone)
  file = request.FILES.get('shouKuanMa')
  type(file)
  print(file.name.split('.')[-1])
  print(file.name)
  filename='wxshouKuanMa'+'.'+file.name.split('.')[-1]
  if file:
    filepath = os.path.join(settings.BASE_DIR, settings.MEDIA_ROOT, phone)
    if not os.path.exists(filepath):
      os.makedirs(filepath)
    _filepath = os.path.join(filepath, filename)
    print(_filepath)
    with open(_filepath,'wb') as newfile:
      for chunk in file.chunks():
        newfile.write(chunk)
    #将文件路径写入数据库avatar字段中
    user=User.objects.filter(phonenum=phone).first()
    print('*************',user.wx.wxskm)
    user.wx.wxskm=_filepath
    print('*************', user.wx.wxskm)
    user.wx.save()
    result = {'code': 200, 'res': '上传微信收款码成功!!!'}
    return render_json(data=result)
def upload_zfbShouKuanMa(request):
  """上传支付宝收款码"""
  phone = request.POST.get('phone')
  print(phone)
  file = request.FILES.get('shouKuanMa')
  # type(file)
  print(file.name.split('.')[-1])
  print(file.name)
  filename='zfbshouKuanMa'+'.'+file.name.split('.')[-1]
  if file:
    filepath = os.path.join(settings.BASE_DIR, settings.MEDIA_ROOT, phone)
    if not os.path.exists(filepath):
      os.makedirs(filepath)
    _filepath = os.path.join(filepath, filename)
    print(_filepath)
    with open(_filepath,'wb') as newfile:
      for chunk in file.chunks():
        newfile.write(chunk)
    #将文件路径写入数据库avatar字段中
    user=User.objects.filter(phonenum=phone).first()
    print('*************',user.ali.aliskm)
    user.ali.aliskm=_filepath
    print('*************', user.ali.aliskm)
    user.ali.save()
    result = {'code': 200, 'res': '上传微信收款码成功!!!'}
    return render_json(data=result)

def get_card_state(request):
  """获取收款码状态"""
  json_str = request.body
  if not json_str:
    result = {'code': 100, 'error': 'Please POST data!!!'}
    return render_json(result)
  json_obj = json.loads(json_str)
  print(json_obj)
  phonenum = json_obj.get('username')
  keys = json_obj.get('keys')
  user=User.objects.filter(phonenum=phonenum,key=keys).first()
  result = {'username': phonenum,
            'has_wx': user.has_wx,
            'has_ali': user.has_ali,
            'has_yhk': user.has_yhk,
            }
  return render_json(data=result)

def get_wx_detail(request):
  """获取wx收款码状态"""
  json_str = request.body
  if not json_str:
    result = {'code': 100, 'error': 'Please POST data!!!'}
    return render_json(result)
  json_obj = json.loads(json_str)
  print(json_obj)
  phonenum = json_obj.get('username')
  keys = json_obj.get('keys')
  user=User.objects.filter(phonenum=phonenum,key=keys).only('has_wx').first()
  if user:
    result = {'username': phonenum,
              'has_wx': user.has_wx,
              'wxname': user.wx.wxname,
              'wxnum': user.wx.wxnum,
              'wxskm': user.wx.wxskm,
              }
    return render_json(data=result)
  else:
    result={'error':'手机号或交易密码不正确'}
    return render_json(data=result,code=101)
def get_ali_detail(request):
  """获取zfb收款码状态"""
  json_str = request.body
  if not json_str:
    result = {'code': 100, 'error': 'Please POST data!!!'}
    return render_json(result)
  json_obj = json.loads(json_str)
  print(json_obj)
  phonenum = json_obj.get('username')
  keys = json_obj.get('keys')
  user=User.objects.filter(phonenum=phonenum,key=keys).only('has_ali').first()
  if user:
    result = {'username': phonenum,
              'has_ali': user.has_ali,
              'aliname': user.ali.aliname,
              'alinum': user.ali.alinum,
              'aliskm': user.ali.aliskm,
              }
    return render_json(data=result)
  else:
    result={'error':'手机号或交易密码不正确'}
    return render_json(data=result,code=101)
def get_yhk_detail(request):
  """获取yhk状态"""
  json_str = request.body
  if not json_str:
    result = {'code': 100, 'error': 'Please POST data!!!'}
    return render_json(result)
  json_obj = json.loads(json_str)
  print(json_obj)
  phonenum = json_obj.get('username')
  keys = json_obj.get('keys')
  user=User.objects.filter(phonenum=phonenum,key=keys).only('has_yhk').first()
  if user:
    result = {'username': phonenum,
              'has_yhk': user.has_yhk,
              'yhname': user.yinghang.yhname,
              'yhnum': user.yinghang.yhnum,
              'yinghang': user.yinghang.yinghang,
              }
    return render_json(data=result)
  else:
    result={'error':'手机号或交易密码不正确'}
    return render_json(data=result,code=101)
def get_renzheng_detail(request):
  """获取实名认证状态"""
  json_str = request.body
  if not json_str:
    result = {'code': 100, 'error': 'Please POST data!!!'}
    return render_json(result)
  json_obj = json.loads(json_str)
  print(json_obj)
  phonenum = json_obj.get('phone')
  keys = json_obj.get('keys')
  user=User.objects.filter(phonenum=phonenum,key=keys).only('phonenum').first()
  print(user, "***************")
  if user:
    result = {
              'idname': user.renzheng.idname,
              'idcard': user.renzheng.idcard,
              'has_renzheng': user.has_renzheng,
              }
    return render_json(data=result)
  else:
    result={'error':'手机号或交易密码不正确'}
    return render_json(data=result,code=101)
def get_recommend_detail(request):
  """获取团队信息"""
  json_str = request.body
  if not json_str:
    result = {'code': 100, 'error': 'Please POST data!!!'}
    return render_json(result)
  json_obj = json.loads(json_str)
  print(json_obj)
  phonenum = json_obj.get('username')
  keys = json_obj.get('keys')
  print('1111111111111')
  user=User.objects.filter(phonenum=phonenum,key=keys).first()
  print(user,'1111111111111')
  if user:
    data,total=_children(phonenum)
    result = {'res': data,'total':total}
    return render_json(data=result)
  else:
    result={'error':'手机号或交易密码不正确'}
    return render_json(data=result,code=101)

def add_wx(request):
  """添加微信收款账户"""
  json_str = request.body
  if not json_str:
    result = {'code': 100, 'error': 'Please POST data!!!'}
    return render_json(result)
  json_obj = json.loads(json_str)
  print(json_obj)
  phonenum = json_obj.get('username')
  wxname = json_obj.get('wxname')
  wxnum = json_obj.get('wxnum')
  jypasswd = json_obj.get('jypasswd')
  jykey = json_obj.get('jykey')
  jypass=tools.hmac_md5(key=jykey,s=jypasswd)
  print(jypass)
  user=User.objects.filter(phonenum=phonenum,jypasswd=jypass).first()
  print(user,"***************")
  if user:
    user.wx.wxname=wxname
    user.wx.wxnum=wxnum
    user.wx.save()
    user.has_wx=True
    user.save()
    result = {'code': 200, 'res': '设置微信账号成功!!!'}
    return render_json(data=result)
  else:
    result = {'code': 103, 'res': '手机号或交易密码不正确'}
    return render_json(data=result,code=103)
def add_zfb(request):
  """添加支付宝收款账户"""
  json_str = request.body
  if not json_str:
    result = {'code': 100, 'error': 'Please POST data!!!'}
    return render_json(result)
  json_obj = json.loads(json_str)
  print(json_obj)
  phonenum = json_obj.get('username')
  aliname = json_obj.get('aliname')
  alinum = json_obj.get('alinum')
  jypasswd = json_obj.get('jypasswd')
  key = json_obj.get('jykey')
  jypass=tools.hmac_md5(key=key,s=jypasswd)
  print(jypass)
  user=User.objects.filter(phonenum=phonenum,jypasswd=jypass).first()
  print(user,"***************")
  if user:
    user.ali.aliname=aliname
    user.ali.alinum=alinum
    user.ali.save()
    user.has_ali = True
    user.save()
    result = {'code': 200, 'res': '设置支付宝账号成功!!!'}
    return render_json(data=result)
  else:
    result = {'code': 101, 'res': '手机号或交易密码不正确'}
    return render_json(data=result, code=103)
def add_yhk(request):
  """添加银行卡收款账户"""
  json_str = request.body
  if not json_str:
    result = {'code': 203, 'error': 'Please POST data!!!'}
    return render_json(result)
  json_obj = json.loads(json_str)
  print(json_obj)
  phonenum = json_obj.get('username')
  yhkname = json_obj.get('yhkname')
  yhknum = json_obj.get('yhknum')
  yinghang = json_obj.get('yinghang')
  jypasswd = json_obj.get('jypasswd')
  jykey = json_obj.get('jykey')
  jypass=tools.hmac_md5(key=jykey,s=jypasswd)
  print(jypass)
  user=User.objects.filter(phonenum=phonenum,jypasswd=jypass).first()
  print(user,"***************")
  if user:
    user.yinghang.yhname = yhkname
    user.yinghang.yhnum = yhknum
    user.yinghang.yinghang = yinghang
    user.yinghang.save()
    user.has_yhk = True
    user.save()
    result = {'code': 200, 'res': '设置银行卡账号成功!!!'}
    return render_json(data=result)
  else:
    result = {'code': 101, 'res': '手机号或交易密码不正确'}
    return render_json(data=result, code=103)
def add_idcard(request):
  """添加实名认证"""
  json_str = request.body
  if not json_str:
    result = {'code': 203, 'error': 'Please POST data!!!'}
    return render_json(result)
  json_obj = json.loads(json_str)
  print(json_obj)
  phonenum = json_obj.get('phone')
  username = json_obj.get('username')
  idnum = json_obj.get('idnum')
  jypasswd = json_obj.get('jypasswd')
  jykey = json_obj.get('jykey')
  jypass=tools.hmac_md5(key=jykey,s=jypasswd)
  print(jypass)
  user=User.objects.filter(phonenum=phonenum,jypasswd=jypass).only('id').first()
  print(user,"***************")
  if user:
    user.renzheng.idname = username
    user.renzheng.idcard = idnum
    user.renzheng.save()
    user.has_renzheng = True
    user.save()
    result = {'code': 200, 'res': '设置银行卡账号成功!!!'}
    return render_json(data=result)
  else:
    result = {'code': 101, 'res': '手机号或交易密码不正确'}
    return render_json(data=result, code=103)

def modify_username(request):
  """修改用户昵称"""
  json_str = request.body
  if not json_str:
    result = {'code': 1, 'error': 'Please POST data!!!'}
    return render_json(result)
  json_obj = json.loads(json_str)
  print(json_obj)
  phonenum = json_obj.get('phonenum')
  nickname = json_obj.get('nickname')
  try:
    User.objects.filter(phonenum=phonenum).only('nickname').update(nickname=nickname)
    result = {'code': 200, 'res': '修改用户昵称成功!!!'}
    return render_json(result)
  except:
    result = {'code': 2, 'res': '修改用户昵称失败!!!'}
    return render_json(data=result,code=2)

#以下是Prem  model的数据库操作
def perm(request):
  if request.method == 'POST':
    json_str = request.body
    json_obj = json.loads(json_str)
    print(json_obj)
    mode = json_obj.get('prem_mode')
    if mode=='list':
      perms=Permission.objects.all()
      data=[p.to_dict() for p in perms]
      return render_json(data=data)
    if mode=='tree':
      level1_perm = Permission.objects.filter(level=1)
      perm_list=perm_children(level1_perm)

      return render_json(data=perm_list)

def roles(request):
  all_roles = Roles.objects.all()
  # print(all_roles)
  role_list = []
  for role in all_roles:
    print(role.id,role.role_name)
    data=role.to_dict()
    relations = RolePermRelation.objects.filter(role_id=role.id)
    perm_id_list = [r.perm_id for r in relations]
    level1_perm = Permission.objects.filter(level=1,id__in=perm_id_list)
    perm_list = perm_children(level1_perm)
    data['children']=perm_list
    role_list.append(data)
  return render_json(role_list)

# 工具函数 检查一级权限下的子权限
def perm_children(level1_perm):
  perm_list = []
  for p1 in level1_perm:
    data = p1.to_dict()
    level2_perm = Permission.objects.filter(level=2, pid=p1.id)
    # data.children=[p.to_dict() for p in level2_perm]
    data['children'] = []
    for p2 in level2_perm:
      child = p2.to_dict()
      level3_perm = Permission.objects.filter(level=3, pid=p2.id)
      child['children'] = [p3.to_dict() for p3 in level3_perm]
      data['children'].append(child)
    perm_list.append(data)
  return perm_list

def _children(parent_phone):
  """查团队下3级"""
  level1_children = User.objects.filter(recommend=parent_phone)
  l1_num=level1_children.count()
  total=l1_num
  children_list=[]
  if level1_children:
    for p1 in level1_children:
      data = p1.to_dict()
      level2_children = User.objects.filter(recommend=p1.phonenum)
      l2_num=level2_children.count()
      total+=l2_num
      data['children'] = []
      if level2_children:
        for p2 in level2_children:
          child = p2.to_dict()
          level3_children = User.objects.filter(recommend=p2.phonenum)
          l3_num=level3_children.count()
          total+=l3_num
          child['children'] = [p3.to_dict() for p3 in level3_children]
          data['children'].append(child)
      children_list.append(data)
  return children_list,total